﻿/* 6. Write a program that reads two integer numbers N and K and an array of N elements from the console. 
 * Find in the array those K elements that have maximal sum. */

using System;

public class SubarrayWithMaxSum
{
    public static void Main()
    {
        int n;
        int k;
        double[] array;

        Console.Write("\nN = ");
        n = int.Parse(Console.ReadLine());
        Console.Write("K = ");
        k = int.Parse(Console.ReadLine());

        if ((n <= 0) || (k <= 0) || (n < k))
            Console.WriteLine("\nSome of conditions N and K are naturals and K < N are not complied!\n");
        else
        {
            array = new double[n];

            Console.WriteLine();
            for (int i = 0; i < n; i++)
            {
                Console.Write("Array[{0}] = ", i);
                array[i] = double.Parse(Console.ReadLine());
            }

            SelectionSort(array);
            Console.Write("\nOne of all {0}-element subarrays with maximal sum is\n {1} {2}", k, "{", array[n - 1]);
            for (int i = 1; i < k; i++)
                Console.Write(", {0}", array[n - i - 1]);

            Console.WriteLine(" {0}\n", "}");
        }
    }

    public static void SelectionSort(double[] array)
    {
        int indexOfCurrentMinElement;

        for (int i = 0; i < array.Length; i++)
        {
            indexOfCurrentMinElement = i;
            for (int j = i + 1; j < array.Length; j++)
                if (array[j] < array[indexOfCurrentMinElement])
                    indexOfCurrentMinElement = j;

            if (indexOfCurrentMinElement != i)
                Swap(array, i, indexOfCurrentMinElement);
        }
    }

    public static void Swap(double[] array, int i, int j)
    {
        double temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}